<?php

namespace App\Admin\Controllers;

use App\Handlers\SlugTranslateHandler;
use App\Models\Article;
use App\Models\Category;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use App\Admin\Extensions\Tools\makeSubTitle;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class ArticleController extends AdminController
{
    protected function title()
    {
        return '文章';
    }

    protected function grid()
    {
        $grid = new Grid(new Article);

        $grid->model()->orderBy('id', 'desc');
        $grid->column('id', 'ID')->sortable();
        $grid->column('title', '标题')->display(function ($title) {
            $url = url('p') . '/' . $this->id;
            $str = '<a target="_blank" href="' . $url . '">' . $title . '</a>';
            if (!empty($this->password)) {
                $str .= '&nbsp;&nbsp;&nbsp;<i class="glyphicon glyphicon-lock"></i>';
            }

            return $str;
        });
        $grid->column('category.name', '所属分类')->sortable();
        $grid->column('is_publish', '是否发布')->switch(Article::PUBLISH_STATE);
        $grid->column('view_count', '浏览量')->sortable();
        $grid->column('created_at', '创建时间')->sortable();
        $grid->column('view_at', '最后阅读时间')->sortable();
        $grid->filter(function(Grid\Filter $filter){
            $filter->expand = false;
            $filter->column(1/2, function (Grid\Filter $filter) {
                $filter->like('title', '标题');
                $filter->equal('cid', '分类')->select(Category::selectOptions());
            });
            $filter->column(1/2, function (Grid\Filter $filter) {
                $filter->between('created_at', '创建时间')->datetime();
            });
        });

        return $grid;
    }

    protected function form()
    {
        $form = new Form(new Article);

        // 去除Root
        $category = Arr::except(Category::selectOptions(), ['0']);
        $form->select('cid', '分类')->options($category)->rules('required');
        $form->hidden('top_cid');
        $form->text('title', '标题')->rules('required|max:100');
        $form->text('subtitle', '副标题')
            ->prepend(new makeSubTitle())
            ->rules('required')
            ->help('默认调用百度翻译为英文，拼音为备选');
        $form->tags('keywords', '关键字');
        $form->switch('is_publish', '发布')->states(Article::PUBLISH_STATE);
        $form->text('password', '阅读密码')->icon('fa-eye');
        $form->textarea('description', '摘要');
        $form->editor('content', '内容')->rules('required');
        $form->image('thumb', '缩略图(封面)')->move($this->imagePath())->removable();
        $form->text('copyfrom', '来源');
        $form->text('author', '作者')->default('Jesse')->rules('required|max:20');
        $form->text('copyright', '底部说明')->default('本文出自 ' . config("admin.name") . '，转载时请注明出处及相应链接。');

        $form->saving(function(Form $form) {
            if (request('cid')) {
                $category = Category::where('id', $form->cid)->first(['id','pid']);
                $form->top_cid = $category->pid ? : $category->id;
            }
        });

        return $form;
    }

    /**
     * 检查副标题是否有重复
     */
    public function checkSubTitle(Article $article, Request $request)
    {
        $count = $article->where('subtitle', $request->subtitle)->count();
        if ($count > 0) {
            return error(4001, '副标题有重复');
        } else {
            return success('副标题可以使用');
        }
    }

    /**
     * 通过百度翻译和拼音转换成字母
     */
    public function makeSubTitle(SlugTranslateHandler $translate, Request $request)
    {
        $slug = $translate->translate($request->title);
        return success('翻译成功', compact('slug'));
    }
}
